﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;

namespace WebSite.Server
{
    /// <summary>
    /// DraftUpload 的摘要说明
    /// </summary>
    public class DraftUpload : IHttpHandler
    {

        public void ProcessRequest( HttpContext context )
        {
            HttpPostedFile file = context.Request.Files["Filedata"];
            
            if (file.ContentLength > 500 * 1024)
            {
                context.Response.StatusCode = 500;
                context.Response.Write( "文件超过500K" );
                return;
            }

            try
            {
                Image img = Image.FromStream( file.InputStream );
            }
            catch
            {
                context.Response.Write( "上传文件失败" );
            }

            const string relateFolder = "/UploadImages/Draft/";
            string phyFolder = HttpContext.Current.Server.MapPath( relateFolder );

            string fileName = System.Guid.NewGuid().ToString( "N" ) + Path.GetExtension( file.FileName );

            if (file != null)
            {
                if (!Directory.Exists( phyFolder ))
                {
                    Directory.CreateDirectory( phyFolder );
                }
                var filename = System.Guid.NewGuid().ToString( "N" ) + Path.GetExtension( file.FileName );
                file.SaveAs( phyFolder + filename );
                //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                context.Response.Write( relateFolder + filename );
            }
            else
            {
                context.Response.Write( "上传文件失败" );
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}